// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements.  See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership.  The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License.  You may obtain a copy of the License at
//
//   http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied.  See the License for the
// specific language governing permissions and limitations
// under the License.

package org.apache.doris.service.arrowflight.sessions;

import org.apache.doris.qe.ConnectContext;
import org.apache.doris.qe.ConnectContext.ConnectType;
import org.apache.doris.qe.ConnectPoolMgr;

import com.google.common.collect.Maps;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import java.util.Map;

public class FlightSqlConnectPoolMgr extends ConnectPoolMgr {
    private static final Logger LOG = LogManager.getLogger(
            FlightSqlConnectPoolMgr.class);
    private final Map<String, Integer> flightToken2ConnectionId = Maps.newConcurrentMap();

    public FlightSqlConnectPoolMgr(int maxConnections) {
        super(maxConnections);
    }

    // Register one connection with its connection id.
    // Return -1 means register OK
    // Return >=0 means register failed, and return value is current connection num.
    @Override
    public int registerConnection(ConnectContext ctx) {
        if (numberConnection.incrementAndGet() > maxConnections) {
            numberConnection.decrementAndGet();
            return numberConnection.get();
        }
        // not check user
        connectionMap.put(ctx.getConnectionId(), ctx);
        if (ctx.getConnectType().equals(ConnectType.ARROW_FLIGHT_SQL)) {
            flightToken2ConnectionId.put(ctx.getPeerIdentity(), ctx.getConnectionId());
        }
        return -1;
    }

    @Override
    public void unregisterConnection(ConnectContext ctx) {
        ctx.closeTxn();
        if (connectionMap.remove(ctx.getConnectionId()) != null) {
            numberConnection.decrementAndGet();
            if (ctx.getConnectType().equals(ConnectType.ARROW_FLIGHT_SQL)) {
                flightToken2ConnectionId.remove(ctx.getPeerIdentity());
            }
        }
    }

    public ConnectContext getContextWithFlightToken(String flightToken) {
        if (flightToken2ConnectionId.containsKey(flightToken)) {
            int connectionId = flightToken2ConnectionId.get(flightToken);
            return getContext(connectionId);
        }
        return null;
    }
}
